/**
 * GTCounterControl.m
 *
 * The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License 
 * at http://www.mozilla.org/MPL/
 * Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
 * either express or implied. See the License for the specific language governing rights and limitations 
 * under the License.
 *
 * The Original Code is gcast-toolbox4iphone.
 *
 * The Initial Developers of the Original Code is Giannandrea Castaldi.
 */
#import "GTCounterControl.h"
#import "GTAlertUtil.h"

#define DECREMENT_BUTTON 0
#define COUNTER 1
#define INCREMENT_BUTTON 2

@interface GTCounterControl ()
- (void)segmentAction:(id)sender;
@end

@implementation GTCounterControl
@synthesize count;
@synthesize delegate;

- (id)initWithCount:(NSInteger)countValue {
  if ((self = [super init])) {
    count = countValue;
    self.backgroundColor = [UIColor clearColor];
    
    // INIT segmented control
    segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects: @"-", [NSString stringWithFormat:@"%d", count], @"+", nil]];
    segmentedControl.segmentedControlStyle = UISegmentedControlStylePlain;
    segmentedControl.frame = CGRectMake(2.0, 2.0, 136.0, 32.0);
    [segmentedControl setWidth:30.0 forSegmentAtIndex:COUNTER];
    segmentedControl.momentary = TRUE;
    [segmentedControl setEnabled:FALSE forSegmentAtIndex:1];
    [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self addSubview:segmentedControl];
  }
  return self;
}

- (void)dealloc {
  [segmentedControl release];
  [delegate release];
  [super dealloc];
}

- (void)setOrigin:(CGPoint)origin {
  self.frame = CGRectMake(origin.x, origin.y, 140.0, 36.0);
}

- (void)segmentAction:(id)sender {
  switch (segmentedControl.selectedSegmentIndex) {
    case DECREMENT_BUTTON: {
      NSString *alert = nil;
      if (!delegate || [delegate canDecrease:self message:&alert]) {
        count--;
      }
      else if (alert) {
        [GTAlertUtil showAlertWithMessage:alert];
      }
      [segmentedControl setTitle:[NSString stringWithFormat:@"%d", count] forSegmentAtIndex:COUNTER];
      break;
    }
    case INCREMENT_BUTTON: {
      NSString *alert = nil;
      if (!delegate || [delegate canIncrese:self message:&alert]) {
        count++;
      }
      else if (alert) {
        [GTAlertUtil showAlertWithMessage:alert];
      }
      [segmentedControl setTitle:[NSString stringWithFormat:@"%d", count] forSegmentAtIndex:COUNTER];
      break;
    }
  }
}

@end
